#include "vtor_life_game.h"

#ifdef __VTOR_LIFE_GAME__


int8_t VtorLifeGame_GetAroundLife(VtorLifeGame* game, int16_t x, int16_t y)
{
	int8_t lifeCnt = 0;
	lifeCnt += VtorBitMap_GetElement(game->showMap, x - 1, y - 1);
	lifeCnt += VtorBitMap_GetElement(game->showMap, x, y - 1);
	lifeCnt += VtorBitMap_GetElement(game->showMap, x + 1, y - 1);

	lifeCnt += VtorBitMap_GetElement(game->showMap, x - 1, y);
	lifeCnt += VtorBitMap_GetElement(game->showMap, x + 1, y);

	lifeCnt += VtorBitMap_GetElement(game->showMap, x - 1, y + 1);
	lifeCnt += VtorBitMap_GetElement(game->showMap, x, y + 1);
	lifeCnt += VtorBitMap_GetElement(game->showMap, x + 1, y + 1);

	return lifeCnt;
}

int8_t VtorLifeGame_Play(VtorLifeGame* game)
{
	// 生命游戏，根据show，修改calc
	for(int y = 0; y < game->calcMap->height; y++)
	{
		for(int x = 0; x < game->calcMap->width; x++)
		{
			int8_t aroundLifeCnt = VtorLifeGame_GetAroundLife(game, x, y);
			int8_t curLife = VtorBitMap_GetElement(game->showMap, x, y);
			if(curLife)
			{
				if(aroundLifeCnt < 2 || aroundLifeCnt > 3)
				{
					VtorBitMap_SetElement(game->calcMap, x, y, 0);
				}
			}
			else
			{
				if(aroundLifeCnt == 3)
				{
					VtorBitMap_SetElement(game->calcMap, x, y, 1);
				}
			}
		}
	}

	memcpy(game->showMap->data, game->calcMap->data,
		game->calcMap->width * game->calcMap->height / 8);

	// 应该可以使用指针交换，但还不清楚失败的原因
	//VtorBitMap* tempBitMap = game->showMap;
	//game->showMap = game->calcMap;
	//game->calcMap = tempBitMap;

}

void VtorLifeGame_Draw(VtorLifeGame* game)
{
	VtorBitMap_Draw(game->showMap);
}


#endif // __VTOR_LIFE_GAME__


